//
//  JDAddShopcartView.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/23.
//

import UIKit
import SwiftyJSON
import ProgressHUD

enum JDAddType {
    case shopcart
    case buy
}
/// 加入购物车  立即购买
class JDAddShopcartView: UIView {

    var goodsLogoUrl: String?
    var goodsDetailModel: JDGoodsDetailModel?
    var basePrice: Double?
    var baseVC: UIViewController?
    var addType: JDAddType = .shopcart

    var containerView: UIView?
    var addShopcartButton: UIButton?
    var closeButton: UIButton?
    var numberTitleLabel: UILabel?
    var numberView: JDNumberInputView?
    
    var bottomSpecView: WJBLabelMarkView?
    var bottomSpecTitleLabel: UILabel?
    
    var topSpecView: WJBLabelMarkView?
    var topSpecTitleLabel: UILabel?
    
    var specPriceLabel: UILabel?
    var qiLabel: UILabel?
    
    var topSelectedId: String?
    var topSkuName: String?
    var bottomSelectedId: String?
    var bottomSkuName: String?
    
    var goodsSkuList: [JDGoodsSkuModel?]?
    var goodsSpecModels :[JDGoodsSpecModel?]? {
        didSet {
            self.zeroSelected()
            self.setupUIElements()
            self.containerView?.layoutIfNeeded()
            self.containerView?.makeBezierPathCorner(UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue|UIRectCorner.topRight.rawValue), 8)
            self.bringSubviewToFront(self.containerView!)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, screenWidth, screenHeight))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func zeroSelected() {
        for subSpecModel in self.goodsSpecModels ?? [JDGoodsSpecModel?]() {
            for detailModel in subSpecModel?.specificationList ?? [JDGoodsSpecDetailModel]() {
                detailModel.isSelected = false
                detailModel.isCanSelected = true
            }
        }
    }
    
    func setupUIElements() {
        self.containerView = UIView()
        self.addSubview(self.containerView!)
        self.containerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self)
            make.bottom.equalTo(self)
        })
        self.containerView?.backgroundColor = .white
        
        let blackView = UIView()
        self.addSubview(blackView)
        blackView.snp.makeConstraints { make in
            make.left.right.equalTo(self)
            make.top.equalTo(self)
            make.bottom.equalTo(self.containerView!.snp.top).offset(4)
        }
        blackView.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(closeButtonAction))
        blackView.addGestureRecognizer(tap)
        
        
        self.addShopcartButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.addShopcartButton!)
        self.addShopcartButton?.snp.makeConstraints({ make in
            make.bottom.equalTo(self).offset(-25-17)
            make.right.equalTo(self.containerView!).offset(-24)
            make.size.equalTo(CGSize(width: 123, height: 48))
        })
        self.addShopcartButton?.layer.cornerRadius = 24
        
        if self.addType == .shopcart {
            self.addShopcartButton?.layer.borderWidth = 1
            self.addShopcartButton?.layer.borderColor = color("#FA6161").cgColor
            self.addShopcartButton?.setTitle("加入购物车", for: .normal)
            self.addShopcartButton?.setTitleColor(color("#FA6161"), for: .normal)
            self.addShopcartButton?.addTarget(self, action: #selector(addShopCartAction), for: .touchUpInside)
        } else {
            self.addShopcartButton?.backgroundColor = color("#FA6161")
            self.addShopcartButton?.setTitle("立即购买", for: .normal)
            self.addShopcartButton?.setTitleColor(.white, for: .normal)
            self.addShopcartButton?.addTarget(self, action: #selector(buyAtOnceAction), for: .touchUpInside)
        }
        self.addShopcartButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        
        
        self.specPriceLabel = UILabel()
        self.containerView?.addSubview(specPriceLabel!)
        self.specPriceLabel?.snp.makeConstraints({ make in
            make.bottom.equalTo(self.addShopcartButton!)//.offset(-5)
            make.left.equalTo(self.containerView!).offset(24)
        })
        self.specPriceLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 20, weight: .semibold), textColor: color("#FA6161"), numberOfLines: 1)
        self.specPriceLabel?.text = String(format: "￥%.2f", self.basePrice ?? 0.00)
        self.specPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
        
        
        self.qiLabel = UILabel()
        self.containerView?.addSubview(self.qiLabel!)
        self.qiLabel?.snp.makeConstraints({ make in
            make.bottom.equalTo(self.specPriceLabel!).offset(-3.5)
            make.left.equalTo(self.specPriceLabel!.snp.right).offset(5)
        })
        self.qiLabel?.text = "起"
        self.qiLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        
        let specPriceTitle = UILabel()
        self.containerView?.addSubview(specPriceTitle)
        specPriceTitle.snp.makeConstraints { make in
            make.left.equalTo(self.specPriceLabel!)
            make.top.equalTo(self.addShopcartButton!)//.offset(5)
        }
        specPriceTitle.text = "小计"
        specPriceTitle.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        
        self.numberTitleLabel = UILabel()
        self.containerView?.addSubview(self.numberTitleLabel!)
        self.numberTitleLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self).offset(24)
            make.bottom.equalTo(self.addShopcartButton!.snp.top).offset(-40)
        })
        self.numberTitleLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"))
        self.numberTitleLabel?.text = "数量"
        
        self.numberView = JDNumberInputView()
        self.containerView?.addSubview(self.numberView!)
        self.numberView?.snp.makeConstraints({ make in
            make.right.equalTo(self.containerView!).offset(-24)
            make.centerY.equalTo(self.numberTitleLabel!)
            make.size.equalTo(CGSize(width: 150, height: 42))
        })
        self.numberView?.backgroundColor = color("#F5F6F8")
        self.numberView?.plusActionBlock = {[weak self] number in
            self?.calculatePrice(number)
        }

        self.numberView?.minusActionBlock = {[weak self] number in
            self?.calculatePrice(number)
        }
        
        //-- - - -- - - - - - -new - -- -- - - -
        let lastSpecModel = self.goodsSpecModels?.last??.specificationList?.first
         
        self.bottomSpecView = WJBLabelMarkView()
        self.containerView?.addSubview(self.bottomSpecView!)
        self.bottomSpecView?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView!).offset(24)
            make.right.equalTo(self.containerView!).offset(-24)
            make.bottom.equalTo(self.numberView!.snp.top).offset(-22)
            make.height.equalTo(1)
        })
        
        if (lastSpecModel?.specificationImage?.count ?? 0) > 0 {
            self.bottomSpecView?.textFont = UIFont.systemFont(ofSize: 16, weight: .regular)
            self.bottomSpecView?.fixedHeight = 55
            self.bottomSpecView?.cornerRadius = 0
            self.bottomSpecView?.layout.interitemSpacing = 10
            self.bottomSpecView?.extraWidth = 12
            self.bottomSpecView?.extraInsertWidth = 50
        } else {
            self.bottomSpecView?.textFont = UIFont.systemFont(ofSize: 16, weight: .regular)
            self.bottomSpecView?.fixedHeight = 42
            self.bottomSpecView?.cornerRadius = 0
            self.bottomSpecView?.layout.interitemSpacing = 10
            self.bottomSpecView?.extraWidth = 12
            self.bottomSpecView?.extraInsertWidth = 0
        }
        
        self.bottomSpecView?.markString = "bottom"
        self.bottomSpecView?.myDelegate = self
        
        var bottomTitleArray = [String]()
        for detailModel in self.goodsSpecModels?.last??.specificationList ?? [JDGoodsSpecDetailModel]() {
            bottomTitleArray.append(detailModel.specificationName ?? "默认规格")
        }
        
        self.bottomSpecView?.dataSource = bottomTitleArray
        self.bottomSpecView?.layoutIfNeeded()
        self.bottomSpecView?.snp.updateConstraints({ make in
            make.height.equalTo(self.bottomSpecView?.layout.sectionHeight ?? 0)
        })
                
        self.bottomSpecTitleLabel = UILabel()
        self.containerView?.addSubview(self.bottomSpecTitleLabel!)
        self.bottomSpecTitleLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"), numberOfLines: 0)
        self.bottomSpecTitleLabel?.text = self.goodsSpecModels?.last??.specificationGroupName ?? "商品规格"
        

        if (self.goodsSpecModels?.count ?? 0) > 1 {
            
            self.bottomSpecTitleLabel?.snp.makeConstraints({ make in
                make.left.equalTo(self.containerView!).offset(24)
                make.bottom.equalTo(self.bottomSpecView!.snp.top).offset(-20)
            })
            
            var topTitleArray = [String]()
            for detailModel in self.goodsSpecModels?.first??.specificationList ?? [JDGoodsSpecDetailModel]() {
                topTitleArray.append(detailModel.specificationName ?? "默认规格")
            }
            
            let firstSpecModel = self.goodsSpecModels?.first??.specificationList?.first
            
            self.topSpecView = WJBLabelMarkView()
            self.containerView?.addSubview(self.topSpecView!)
            self.topSpecView?.snp.makeConstraints({ make in
                make.left.equalTo(self.containerView!).offset(24)
                make.right.equalTo(self.containerView!).offset(-24)
                make.bottom.equalTo(self.bottomSpecTitleLabel!.snp.top).offset(-22)
                make.height.equalTo(1)
            })
            if (firstSpecModel?.specificationImage?.count ?? 0) > 0 {
                self.topSpecView?.textFont = UIFont.systemFont(ofSize: 16, weight: .regular)
                self.topSpecView?.fixedHeight = 55
                self.topSpecView?.cornerRadius = 0
                self.topSpecView?.layout.interitemSpacing = 10
                self.topSpecView?.extraWidth = 12
                self.topSpecView?.extraInsertWidth = 50
            } else {
                self.topSpecView?.textFont = UIFont.systemFont(ofSize: 16, weight: .regular)
                self.topSpecView?.fixedHeight = 42
                self.topSpecView?.cornerRadius = 0
                self.topSpecView?.layout.interitemSpacing = 10
                self.topSpecView?.extraWidth = 12
                self.topSpecView?.extraInsertWidth = 0
            }
            
            self.topSpecView?.markString = "top"
            self.topSpecView?.myDelegate = self
            self.topSpecView?.dataSource = topTitleArray
            self.topSpecView?.layoutIfNeeded()
            self.topSpecView?.snp.updateConstraints({ make in
                make.height.equalTo(self.topSpecView?.layout.sectionHeight ?? 0)
            })
            
            self.topSpecTitleLabel = UILabel()
            self.containerView?.addSubview(self.topSpecTitleLabel!)
            self.topSpecTitleLabel?.snp.makeConstraints({ make in
                make.left.equalTo(self.containerView!).offset(24)
                make.bottom.equalTo(self.topSpecView!.snp.top).offset(-20)
                make.top.equalTo(self.containerView!).offset(26)
            })
            self.topSpecTitleLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"), numberOfLines: 0)
            self.topSpecTitleLabel?.text = self.goodsSpecModels?.first??.specificationGroupName ?? "商品规格"
            
            self.closeButton = UIButton(type: .custom)
            self.containerView?.addSubview(self.closeButton!)
            self.closeButton?.snp.makeConstraints({ make in
                make.right.equalTo(self.containerView!).offset(-13)
                make.centerY.equalTo(self.topSpecTitleLabel!)
                make.size.equalTo(CGSizeMake(36, 36))
            })
            self.closeButton?.setImage(UIImage(named: "addShopcart_close"), for: .normal)
            self.closeButton?.addTarget(self, action: #selector(closeButtonAction), for: .touchUpInside)
            
        } else {
            
            self.bottomSpecTitleLabel?.snp.makeConstraints({ make in
                make.left.equalTo(self.containerView!).offset(24)
                make.bottom.equalTo(self.bottomSpecView!.snp.top).offset(-20)
                make.top.equalTo(self.containerView!).offset(26)
            })
            
            self.closeButton = UIButton(type: .custom)
            self.containerView?.addSubview(self.closeButton!)
            self.closeButton?.snp.makeConstraints({ make in
                make.right.equalTo(self.containerView!).offset(-13)
                make.centerY.equalTo(self.bottomSpecTitleLabel!)
                make.size.equalTo(CGSizeMake(36, 36))
            })
            self.closeButton?.setImage(UIImage(named: "addShopcart_close"), for: .normal)
            self.closeButton?.addTarget(self, action: #selector(closeButtonAction), for: .touchUpInside)
        }
    }
    
    func calculatePrice(_ currentNumber: Int) {
        self.specPriceLabel?.text = String(format: "￥%.2f", (self.basePrice ?? 0.00)*CGFloat(currentNumber))
        self.specPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    @objc func addShopCartAction() {
        
        var skuStr = ""
        if JSON(self.bottomSelectedId as Any).intValue >= JSON(self.topSelectedId as Any).intValue {
            skuStr = String.init(format: "%@_%@", self.topSelectedId ?? "", self.bottomSelectedId ?? "")
        } else {
            skuStr = String.init(format: "%@_%@", self.bottomSelectedId ?? "",self.topSelectedId ?? "")
        }
        
        if (self.topSelectedId?.count ?? 0) <= 0 || (self.bottomSelectedId?.count ?? 0) <= 0 {
            skuStr = skuStr.replacingOccurrences(of: "_", with: "")
        }
        
        var skuId = ""
        var goodsId = ""
        for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
            if skuModel?.specificationKey == skuStr {
                goodsId = skuModel?.goodsId ?? ""
                skuId = skuModel?.goodsSkuId ?? ""
            }
        }
        
        if goodsId.count == 0 || skuId.count == 0 {
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "规格有误")
            return
        }
        
        if (self.numberView?.showNumber ?? 0) <= 0 {
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "请选择购买数量")
            return
        }
        

        // 加入购物车接口
        var params = [String: Any]()
        params["goodsId"] = goodsId
        params["goodsSkuId"] = skuId
        params["count"] = self.numberView?.numberInputView.text
        JDNetWorkRequest(.addShopcart(params)) { responseStr in

            printLog("接口返回:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "加入成功")
              
                NotificationCenter.default.post(name: Notification.Name("refreshShopcart"), object: nil)  
                
                self.closeButtonAction()
            } else if commonModel?.code == "01" {
                JDTools.getKeyWindows()?.rootViewController?.view.toast(message: commonModel?.msg ?? "")
            }

        } failure: { error in

        } error: { errorCode in

        }

    }
    
    @objc func buyAtOnceAction() {
        var skuStr = ""
        if JSON(self.bottomSelectedId as Any).intValue >= JSON(self.topSelectedId as Any).intValue {
            skuStr = String.init(format: "%@_%@", self.topSelectedId ?? "", self.bottomSelectedId ?? "")
        } else {
            skuStr = String.init(format: "%@_%@", self.bottomSelectedId ?? "",self.topSelectedId ?? "")
        }
        if (self.topSelectedId?.count ?? 0) <= 0 || (self.bottomSelectedId?.count ?? 0) <= 0 {
            skuStr = skuStr.replacingOccurrences(of: "_", with: "")
        }
        
        var skuId = ""
        var goodsId = ""
        var userSkuModel: JDGoodsSkuModel?
        for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
            if skuModel?.specificationKey == skuStr {
                goodsId = skuModel?.goodsId ?? ""
                skuId = skuModel?.goodsSkuId ?? ""
                userSkuModel = skuModel
            }
        }
        
        if goodsId.count == 0 || skuId.count == 0 {
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "规格有误")
            return
        }
        
        if (self.numberView?.showNumber ?? 0) <= 0 {
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "请选择购买数量")
            return
        }
      
        let goodsInfoModel = JDShopCartGoodsModel()
        goodsInfoModel.goodsName = self.goodsDetailModel?.goodsName//"商品名啊"
        
        var specNameStr = ""
        if (self.topSkuName?.count ?? 0) > 0 {
            specNameStr = String.init(format: "%@,%@", self.topSkuName ?? "",self.bottomSkuName ?? "")
        } else {
            specNameStr = self.bottomSkuName ?? ""
        }
        
        goodsInfoModel.specificationName = specNameStr
        goodsInfoModel.goodsMainImgUrl = self.goodsLogoUrl
        goodsInfoModel.origin = self.goodsDetailModel?.origin
        
        
        goodsInfoModel.salePriceText = userSkuModel?.salePriceText ?? ""
        goodsInfoModel.salePrice = JSON(userSkuModel?.salePrice ?? "0").intValue
        
        
        goodsInfoModel.goodsSkuId = skuId
        goodsInfoModel.goodsId = goodsId
        goodsInfoModel.count = self.numberView?.showNumber ?? 1
        goodsInfoModel.isSelected = true
        
        let submitModel = JDShopCartModel()
//        submitModel.shopId = ""   用不到
//        submitModel.shopName = ""
        submitModel.goodsList = [goodsInfoModel]
        
        self.createPreOrder(submitModel) {[weak self] preOrderModel in
            
            if let preModel = preOrderModel {
                
                let confirmOrderVC = JDNewConfirmOrderViewController()
                confirmOrderVC.selectedShopCartModel = submitModel
                confirmOrderVC.preOrderModel = preModel
                self?.baseVC?.hidesBottomBarPushViewController(confirmOrderVC)
                self?.closeButtonAction()
                
                
//                let confirmOrderVC = JDConfirmOrderViewController()
//                confirmOrderVC.selectedShopCartModel = submitModel
//                confirmOrderVC.preOrderModel = preModel
//                self?.baseVC?.hidesBottomBarPushViewController(confirmOrderVC)
//                self?.closeButtonAction()
            }
        }
    }
    
    // 预订单接口
    func createPreOrder(_ selectedShopCartModel: JDShopCartModel?, completed: @escaping ((JDPreOrderModel?)->())) {
        var selectedGoodsList = [[String: Any]]()
                
        for speGoodsModel in selectedShopCartModel?.goodsList ?? [JDShopCartGoodsModel]() {
            
            if speGoodsModel.isSelected {
                var dic = [String: Any]()
                dic["goodsId"] = speGoodsModel.goodsId
                dic["goodsSkuId"] = speGoodsModel.goodsSkuId
                dic["goodsNum"] = speGoodsModel.count
                selectedGoodsList.append(dic)
            }
            
        }
        
        if selectedGoodsList.count <= 0 {
            return;
        }
        ProgressHUD.animate()
        var params = [String: Any]()
        params["goodsList"] = selectedGoodsList
        JDNetWorkRequest(.preSaveOrder(params)) { responseStr in
            ProgressHUD.dismiss()
            printLog("预订单接口:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let model = JDPreOrderModel.deserialize(from: responseStr, designatedPath: "data") {
                    completed(model)
                } else {
                    JDTools.getKeyWindows()?.rootViewController?.view.toast(message: commonModel?.msg ?? "")
                    completed(nil)
                }
            } else {
                JDTools.getKeyWindows()?.rootViewController?.view.toast(message: commonModel?.msg ?? "")
                completed(nil)
            }
        } failure: { error in
            ProgressHUD.dismiss()
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: error.errorDescription ?? "")
            completed(nil)
        } error: { errorCode in
            ProgressHUD.dismiss()
            JDTools.getKeyWindows()?.rootViewController?.view.toast(message: String(format: "服务器异常:%d", errorCode))
            completed(nil)
        }
    }

    
    @objc func closeButtonAction() {
        self.removeFromSuperview()
        printLog("关闭页面")
    }

}

extension JDAddShopcartView: WJBLabelMarkViewDelegate {
    func customView(cell: UICollectionViewCell, cellForRowAt index: Int, dataSource: [String], markString: String?) {
        
        cell.contentView.makeCorner(4)
        cell.contentView.backgroundColor = color("#F5F6F8")
        
        if markString == "bottom" {
            
            let specModel = self.goodsSpecModels?.last??.specificationList?[index]
            
            if (specModel?.specificationImage?.count ?? 0) > 0 {
                
                let imageV = UIImageView()
                cell.contentView.addSubview(imageV)
                imageV.snp.makeConstraints { make in
                    make.centerY.equalTo(cell.contentView)
                    make.left.equalTo(cell.contentView).offset(12)
                    make.size.equalTo(CGSizeMake(38, 38))
                }
                if specModel?.specificationImage?.hasPrefix("http") ?? false {
                    imageV.kf.setImage(with: URL(string: specModel?.specificationImage ?? ""))
                } else {
                    imageV.downloadImage(specModel?.specificationImage ?? "")
                }
                
                let infoLabel = UILabel()
                cell.contentView.addSubview(infoLabel)
                infoLabel.snp.makeConstraints { make in
                    make.left.equalTo(imageV.snp.right).offset(12)
                    make.centerY.equalTo(cell.contentView)
                }
                infoLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
                infoLabel.text = specModel?.specificationName
                
                if !(specModel?.isCanSelected ?? true) {
                    // 不可选
                    cell.contentView.backgroundColor = color("#F5F6F8")
                    cell.contentView.layer.borderWidth = 0
                    cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                    infoLabel.textColor = color("#C8CCD4")
                } else {
                    if specModel?.isSelected ?? false {
                        cell.contentView.backgroundColor = .white
                        cell.contentView.layer.borderColor = color("#FA6161").cgColor
                        cell.contentView.layer.borderWidth = 1
                        infoLabel.textColor = color("#FA6161")
                    } else {
                        cell.contentView.backgroundColor = .commonColor()
                        cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                        cell.contentView.layer.borderWidth = 0
                        infoLabel.textColor = color("#333333")
                    }
                }
                
            } else {
                let infoLabel = UILabel()
                cell.contentView.addSubview(infoLabel)
                infoLabel.snp.makeConstraints { make in
                    make.centerX.centerY.equalTo(cell.contentView)
                }
                infoLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
                infoLabel.text = specModel?.specificationName
                
                if !(specModel?.isCanSelected ?? true) {
                    // 不可选
                    cell.contentView.backgroundColor = color("#F5F6F8")
                    cell.contentView.layer.borderWidth = 0
                    cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                    infoLabel.textColor = color("#C8CCD4")
                } else {
                    if specModel?.isSelected ?? false {
                        cell.contentView.backgroundColor = .white
                        cell.contentView.layer.borderColor = color("#FA6161").cgColor
                        cell.contentView.layer.borderWidth = 1
                        infoLabel.textColor = color("#FA6161")
                    } else {
                        cell.contentView.backgroundColor = .commonColor()
                        cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                        cell.contentView.layer.borderWidth = 0
                        infoLabel.textColor = color("#333333")
                    }
                }
            }
            
        } else if markString == "top" {
            
            let specModel = self.goodsSpecModels?.first??.specificationList?[index]
            
            if (specModel?.specificationImage?.count ?? 0) > 0 {
                let imageV = UIImageView()
                cell.contentView.addSubview(imageV)
                imageV.snp.makeConstraints { make in
                    make.centerY.equalTo(cell.contentView)
                    make.left.equalTo(cell.contentView).offset(12)
                    make.size.equalTo(CGSizeMake(38, 38))
                }
                if specModel?.specificationImage?.hasPrefix("http") ?? false {
                    imageV.kf.setImage(with: URL(string: specModel?.specificationImage ?? ""))
                } else {
                    imageV.downloadImage(specModel?.specificationImage ?? "")
                }
                
                let infoLabel = UILabel()
                cell.contentView.addSubview(infoLabel)
                infoLabel.snp.makeConstraints { make in
                    make.left.equalTo(imageV.snp.right).offset(12)
                    make.centerY.equalTo(cell.contentView)
                }
                infoLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
                infoLabel.text = specModel?.specificationName
                
                if !(specModel?.isCanSelected ?? true) {
                    // 不可选
                    cell.contentView.backgroundColor = color("#F5F6F8")
                    cell.contentView.layer.borderWidth = 0
                    cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                    infoLabel.textColor = color("#C8CCD4")
                } else {
                    if specModel?.isSelected ?? false {
                        cell.contentView.backgroundColor = .white
                        cell.contentView.layer.borderColor = color("#FA6161").cgColor
                        cell.contentView.layer.borderWidth = 1
                        infoLabel.textColor = color("#FA6161")
                    } else {
                        cell.contentView.backgroundColor = .commonColor()
                        cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                        cell.contentView.layer.borderWidth = 0
                        infoLabel.textColor = color("#333333")
                    }
                }
            } else {
                let infoLabel = UILabel()
                cell.contentView.addSubview(infoLabel)
                infoLabel.snp.makeConstraints { make in
                    make.centerX.centerY.equalTo(cell.contentView)
                }
                infoLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
                infoLabel.text = specModel?.specificationName
                
                if !(specModel?.isCanSelected ?? true) {
                    // 不可选
                    cell.contentView.backgroundColor = color("#F5F6F8")
                    cell.contentView.layer.borderWidth = 0
                    cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                    infoLabel.textColor = color("#C8CCD4")
                } else {
                    if specModel?.isSelected ?? false {
                        cell.contentView.backgroundColor = .white
                        cell.contentView.layer.borderColor = color("#FA6161").cgColor
                        cell.contentView.layer.borderWidth = 1
                        infoLabel.textColor = color("#FA6161")
                    } else {
                        cell.contentView.backgroundColor = .commonColor()
                        cell.contentView.layer.borderColor = color("#F5F6F8").cgColor
                        cell.contentView.layer.borderWidth = 0
                        infoLabel.textColor = color("#333333")
                    }
                }
            }
            
        }
    
    }
    
    func didSelectedAtIndexPath(indexPath: IndexPath, labelText: String, markString: String?) {
        if markString == "bottom" {
            let specModel = self.goodsSpecModels?.last??.specificationList?[indexPath.row]
            
            if specModel?.specificationId == self.bottomSelectedId {
                specModel?.isSelected = false
                self.bottomSelectedId = nil
                self.bottomSkuName = nil
                self.reloadSku()
            } else {
                if specModel?.isCanSelected ?? false {
                    for subSpecModels in self.goodsSpecModels?.last??.specificationList ?? [JDGoodsSpecDetailModel]() {
                        subSpecModels.isSelected = false
                    }
                    specModel?.isSelected = true
                    self.bottomSelectedId = specModel?.specificationId
                    self.bottomSkuName = specModel?.specificationName
                    self.reloadSku()
                }
            }
        } else if markString == "top" {
            let specModel = self.goodsSpecModels?.first??.specificationList?[indexPath.row]
            
            if specModel?.specificationId == self.topSelectedId {
                specModel?.isSelected = false
                self.topSelectedId = nil
                self.topSkuName = nil
                self.reloadSku()
            } else {
                if specModel?.isCanSelected ?? false {
                    for subSpecModels in self.goodsSpecModels?.first??.specificationList ?? [JDGoodsSpecDetailModel]() {
                        subSpecModels.isSelected = false
                    }
                    specModel?.isSelected = true
                    self.topSelectedId = specModel?.specificationId
                    self.topSkuName = specModel?.specificationName
                    self.reloadSku()
                }
            }
        }
        
        self.topSpecView?.myCollectionView?.reloadData()
        self.bottomSpecView?.myCollectionView?.reloadData()
        
        
        print("点击:\(markString):\(indexPath.row)")
    }
}

extension JDAddShopcartView {
    
    func reloadSku() {
        
        let specCount = self.goodsSpecModels?.count ?? 0
        
        // 2行 规格
        if specCount > 1 {
            
            if (self.topSelectedId?.count ?? 0) > 0 && (self.bottomSelectedId?.count ?? 0) <= 0 {
                
                let topSpecModels = self.goodsSpecModels?.first??.specificationList
                for topModel in topSpecModels ?? [JDGoodsSpecDetailModel]() {
                    topModel.isCanSelected = true
                }
                // 先选上面，处理下面
                
                let specModels = self.goodsSpecModels?.last??.specificationList
                for subModel in specModels ?? [JDGoodsSpecDetailModel]() {

                    let currentSpecId = subModel.specificationId
                    var skuStr = ""
                    if JSON(self.topSelectedId as Any).intValue >= JSON(currentSpecId as Any).intValue {
                        skuStr = String.init(format: "%@_%@", currentSpecId ?? "", self.topSelectedId ?? "")
                    } else {
                        skuStr = String.init(format: "%@_%@", self.topSelectedId ?? "",currentSpecId ?? "")
                    }

                    subModel.isCanSelected = false
                    for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                        if (skuModel?.specificationKey ?? "sku") == skuStr {
                            subModel.isCanSelected = true
                        }
                    }
                }
                self.specPriceLabel?.text = String(format: "￥%.2f", self.basePrice ?? 0.00)
                self.specPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
                self.qiLabel?.isHidden = false
            } else if (self.bottomSelectedId?.count ?? 0) > 0 && (self.topSelectedId?.count ?? 0) <= 0 {
                
                let bottomSpecModels = self.goodsSpecModels?.last??.specificationList
                for bottomModel in bottomSpecModels ?? [JDGoodsSpecDetailModel]() {
                    bottomModel.isCanSelected = true
                }
                
                // 先选下面，未选上面
                
                let specModels = self.goodsSpecModels?.first??.specificationList
                for subModel in specModels ?? [JDGoodsSpecDetailModel]() {

                    let currentSpecId = subModel.specificationId
                    var skuStr = ""
                    if JSON(self.bottomSelectedId as Any).intValue >= JSON(currentSpecId as Any).intValue {
                        skuStr = String.init(format: "%@_%@", currentSpecId ?? "", self.bottomSelectedId ?? "")
                    } else {
                        skuStr = String.init(format: "%@_%@", self.bottomSelectedId ?? "",currentSpecId ?? "")
                    }

                    subModel.isCanSelected = false
                    for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                        if (skuModel?.specificationKey ?? "sku") == skuStr {
                            subModel.isCanSelected = true
                        }
                    }
                }
                
                self.specPriceLabel?.text = String(format: "￥%.2f", self.basePrice ?? 0.00)
                self.specPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
                self.qiLabel?.isHidden = false
                
            } else if  (self.bottomSelectedId?.count ?? 0) > 0 && (self.topSelectedId?.count ?? 0) > 0  {
                //选择了2个
                let specModels = self.goodsSpecModels?.last??.specificationList
                for subModel in specModels ?? [JDGoodsSpecDetailModel]() {

                    let currentSpecId = subModel.specificationId
                    var skuStr = ""
                    if JSON(self.topSelectedId as Any).intValue >= JSON(currentSpecId as Any).intValue {
                        skuStr = String.init(format: "%@_%@", currentSpecId ?? "", self.topSelectedId ?? "")
                    } else {
                        skuStr = String.init(format: "%@_%@", self.topSelectedId ?? "",currentSpecId ?? "")
                    }

                    subModel.isCanSelected = false
                    for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                        if (skuModel?.specificationKey ?? "sku") == skuStr {
                            subModel.isCanSelected = true
                        }
                    }
                }
                
                
                let specModelsB = self.goodsSpecModels?.first??.specificationList
                for subModel in specModelsB ?? [JDGoodsSpecDetailModel]() {

                    let currentSpecId = subModel.specificationId
                    var skuStr = ""
                    if JSON(self.bottomSelectedId as Any).intValue >= JSON(currentSpecId as Any).intValue {
                        skuStr = String.init(format: "%@_%@", currentSpecId ?? "", self.bottomSelectedId ?? "")
                    } else {
                        skuStr = String.init(format: "%@_%@", self.bottomSelectedId ?? "",currentSpecId ?? "")
                    }

                    subModel.isCanSelected = false
                    for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                        if (skuModel?.specificationKey ?? "sku") == skuStr {
                            subModel.isCanSelected = true
                        }
                    }
                }
                
                var skuStr = ""
                if JSON(self.bottomSelectedId as Any).intValue >= JSON(self.topSelectedId as Any).intValue {
                    skuStr = String.init(format: "%@_%@", self.topSelectedId ?? "", self.bottomSelectedId ?? "")
                } else {
                    skuStr = String.init(format: "%@_%@", self.bottomSelectedId ?? "",self.topSelectedId ?? "")
                }
                var userSkuModel: JDGoodsSkuModel?
                for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                    if skuModel?.specificationKey == skuStr {
                        userSkuModel = skuModel
                    }
                }
                
                self.specPriceLabel?.text = String(format: "￥%@", userSkuModel?.salePriceText ?? "")
                self.specPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
                self.qiLabel?.isHidden = true
                
            } else {
                
                // 全部还原
                let bottomSpecModels = self.goodsSpecModels?.last??.specificationList
                let topSpecModels = self.goodsSpecModels?.first??.specificationList
                
                
                for topSubModel in topSpecModels ?? [JDGoodsSpecDetailModel]() {
                    topSubModel.isCanSelected = true
                }
                
                for bottomSubModel in bottomSpecModels ?? [JDGoodsSpecDetailModel]() {
                    bottomSubModel.isCanSelected = true
                }
                
            }
        } else if specCount > 0 {
            // 1行 规格
            // 都可以选 不考虑任何东西
            let specModels = self.goodsSpecModels?.last??.specificationList
            for subModel in specModels ?? [JDGoodsSpecDetailModel]() {

                let currentSpecId = subModel.specificationId
//                var skuStr = currentSpecId
                subModel.isCanSelected = false
                for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                    if (skuModel?.specificationKey ?? "sku") == currentSpecId {
                        subModel.isCanSelected = true
                    }
                }
            }
            
            var userSkuModel: JDGoodsSkuModel?
            for skuModel in self.goodsSkuList ?? [JDGoodsSkuModel?]() {
                if skuModel?.specificationKey == self.bottomSelectedId {
                    userSkuModel = skuModel
                }
            }
            
            self.specPriceLabel?.text = String(format: "￥%@", userSkuModel?.salePriceText ?? "")
            self.specPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
            self.qiLabel?.isHidden = true
            
        } else {
            
        }
        
    }
}
